#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests
import MySQLdb
import json


def get_html():
    print 'Html'


def convert(str):
    list = str.split('#')
    g_list = ""
    tag = ""
    for i in list:
        print i.find('$')
        if i.find('$') > 0:
            s_list = i.split('$')
            url = s_list[1]
            tag = s_list[0]
        else:
            url = i

        a = url.find('/', len('http://'))
        host = url[0: a]

        try:
            if 'm3u8' != url[-4:]:
                r = requests.get(url)
                # print r.status_code, r.text
                if r.status_code != 200:
                    print 'requests code ' + r.status_code
                else:
                    x = 'requestToken = "'
                    y = '";'
                    a = r.text.find(x)
                    b = r.text.find('";', a + len(x))
                    s_url = host + '/token/' + r.text[a + len(x):b]
                    k = requests.get(s_url)
                    j = json.loads(k.text)
                    if g_list == "":
                        g_list = tag + "$" + host + j['main']
                    else:
                        g_list = g_list + '#' + tag + "$" + host + j['main']

            else:
                if g_list == "":
                    g_list = tag + "$" + url
                else:
                    g_list = g_list + '#' + tag + "$" + url
        except requests.HTTPError:
            print 'requests error: '

            # print g_list
    # 返回列表
    return g_list


if __name__ == '__main__':
    # 打开数据库连接
    db = MySQLdb.connect("localhost", "root", "root", "cms")

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    cursor.execute("set names utf8")
    # SQL 查询语句
    sql = "SELECT d_id,d_playurl FROM mac_vod"
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            d_id = row[0]
            d_playurl = row[1]
            # 打印结果
            # print d_id, d_playurl
            playUrl = convert(d_playurl)
            print playUrl
            print '---------------------------------------'

            sql = "UPDATE mac_vod SET d_playfrom = 'test' , d_playurl = '" + playUrl + "' WHERE d_id = %d" % d_id
            print sql
            try:
                # 执行SQL语句
                cursor.execute(sql)
                # 提交到数据库执行
                db.commit()
            except:
                # 发生错误时回滚
                db.rollback()

    except:
        print "Error: unable to fecth data"

    # 关闭数据库连接
    db.close()
